import Vue from "vue"
import uniq from "lodash/uniq";
import zipObject from "lodash/zipObject";
import cloneDeep from "lodash/cloneDeep";
import toArray from "lodash/toArray";

const store = {
  state: {
    /**
     * 方案信息
     * name:方案名
     * schemeId:方案ID
     * description:方案描述
     * */
    name:"",
    schemeId:"",
    description:"",
    /**
     * 节点渲染信息，
     * activeNode：前激活节点，
     * openWin：控制是否打开属性编辑窗口
     * */
    editModal: {
      activeNode: "",
      openWin: false,
      currentView: "",
      saveData:true,
      customParams:{}
    },
    /**
     * 保存一个以终点为key的连接对象map
     * nodeRelations: {
     *  '节点ID':['父节点1ID'，'父节点2ID'，'父节点3ID'....]
     * },
     * */
    nodeRelations: {},
    /**
     * connections{
     *   'targetId\\sourceId':connection对象
     * }
     * */
    connections: {},
    /**
     * 保存一个以节点name为key的对象
     * steps: {
     *  '节点Id':'节点DataObject'
     * }
     * */
    steps: {}
  },
  getters: {
    isSave(state){
      return state.editModal.saveData;
    },
    /**
     * 获取所有点的连接信息，return
     * [
     *  {sourceId,targetId},
     *  {sourceId,targetId}
     *  ]
     * */
    connectionInfo(state){
        let {connections}=state,connectionInfo=[];
        for (let key in connections){
          if(connections[key]!=null){
            connectionInfo.push(zipObject(['targetId','sourceId'],key.split("||")))
          }
        }
        return connectionInfo;
    },
    /**
     * 根据当前激活的点获取节点信息
     * */
    activeNodeRelationInfo(state){
      let {nodeRelations:relation,editModal:{activeNode:id}}=state,parentNode=[];
      if(!id||!relation[id]){
        //console.log("节点ID为空，或者未找到关联关系");
        return;
      }
      (function recursConnection(id, connectionInfo, exArray) {
        //元素不存在或者长度为0则不操作
        if (exArray && connectionInfo[id] && connectionInfo[id].length > 0) {
          //先追加列表内的所有steps
          connectionInfo[id].forEach(el => exArray.push(el));
          //根据sourceId找到父节点，然后对每个父节点元素递归,element是一个Connection对象
          connectionInfo[id].map(element => recursConnection(element, connectionInfo, exArray));
        }
      })(id, relation, parentNode);

      return uniq(parentNode);

    },
    /*
    * */
    nodeInfo(state,otherGetter){
      let{steps,editModal:{activeNode:id}}=state,{activeNodeRelationInfo:relationInfo}=otherGetter;
      if (!id || !steps[id]) {
        //console.log("id为空或者未找到step",id ,steps[id]);
        return;
      }
      //获取节点输出属性信息
      let availableFields = [];
      if(relationInfo){
        relationInfo.forEach(function (id) {
          let step = steps[id];
          if (step.outputFields&&Array.isArray(step.outputFields)) {
            step.outputFields.forEach(el => availableFields.push({step:step.name,name:el,stepId:step.id}));
          }
        });
      }
      steps[id].availableFields = availableFields;
      return steps[id];
    },
    kettleJson(state, otherGetter){
      let {steps,name,schemeId:id,description}=state,{connectionInfo}=otherGetter,stepArray= toArray(steps);
      return {
          hops: connectionInfo.map(el => {
            return {from: el.sourceId, to: el.targetId, enabled: "y"}
          }),
          name,id,description,
          steps:stepArray,
          idMapping:stepArray.map((el,index)=>{return {id:el.id,name:el.name+'-('+index+')'}})
      }
    }
  },
  mutations: {
    changeLabel(state,payload){
      let {connections}=state,{id,newId,oldId,labelId}=payload;
      if(oldId){
        connections[oldId+"||"+id].getOverlay(labelId).setLabel("");
      }
      if(newId){
        connections[newId+"||"+id].getOverlay(labelId).setLabel("11111");
      }
    },
    saveData(state,save){
      state.editModal.saveData=save;
    },
    addNode(state, node){
      let {steps}=state, cNode = cloneDeep(node);
      if (steps[cNode.id]) {
        steps[cNode.id] = cNode;
      } else {
        Vue.set(steps, cNode.id, cNode)
      }
    },
    updateXY(state,node){
      let {id,left,top}=node,step=state.steps[id];
      if(step){step.x=left;step.y=top}
    },
    setName(state,name){
      state.name=name;
    },
    setDescription(state,description){
      state.description=description;
    },
    setId(state,id){state.schemeId=id},
    removeNodeById(state, id){
      let {steps,connections}=state;
      //移除关系信息
      Vue.delete(steps, id);
      //jsPlumb删除链接信息
      for (let key in connections ){
        if(key.lastIndexOf(id)!=-1){
          jsPlumb.detach(connections[key]);
        }
      }
    },
    /**
     * connections:jsPlumb connections对象
     * 添加节点 1添加节点对象记录 2添加节点关系记录
     *
     * */
    addConnection(state, connection){
      let  {connections:conns}=state,{targetId,sourceId}=connection,
        key = targetId + "||" + sourceId;
      //判断连接是否已经存在，如果不存在则新添加一条记录
      if (conns[key]) {
        conns[key] = connection;
      }
      else {
        Vue.set(conns, key, connection)
      }
    },
    /**
     * 移除一条connection记录
     * connection:包含targetId和sourceId的对象
     * */
    removeConnection(state, connection) {
      let {connections:conns}=state,{targetId,sourceId}=connection,key=targetId+"||"+sourceId;
      for (let id in conns){
        if (id==key){
          Vue.delete(conns,id);
        }
      }
    },
    addNodeRelations(state, connection){
      let {nodeRelations}=state,{targetId, sourceId}=connection,targetArray=nodeRelations[targetId];
      //添加从属关系到nodeRelations
      if ( targetArray && Array.isArray(targetArray)){
        targetArray.push(sourceId);
      }
      else{
        Vue.set(nodeRelations, targetId, [sourceId]);
      }

    },
    /**
     * 根据targetId删除该ID下的关系记录，包含连入和连出
     * id:targetId or sourceId
     * */
    removeRelationById(state, targetId){
      let {nodeRelations:relations}=state;
      //节点连接出去的关系
      for(let key in relations){
        if(Array.isArray(relations[key])){
          relations[key].forEach((el,index,relations)=>{
            if(el==targetId)
              relations.splice(index,1);
          })
        }
      }
      //连入节点的关系
      if(relations[targetId]){
        Vue.delete(relations,targetId);
      };
    },
    openWin(state, {activeNode = "emptyStep", currentView = "emptyView",customParams}={}){
      if (!state.editModal.openWin) {
        state.editModal.activeNode = activeNode;
        state.editModal.currentView = currentView;
        state.editModal.openWin = true;
        if(customParams)
          Vue.set(state.editModal,"customParams",customParams);
      }
    },
    closeWin(state){
      state.editModal.openWin = false;
      state.editModal.activeNode = "";
    }
  },
  actions: {
    addConnection({commit}, connInfo){
      commit("addConnection", connInfo);
      commit("addNodeRelations", connInfo);
    },
    removeConnection({commit}, connInfo){
      let{targetId}=connInfo;
      //删除链接对象
      commit("removeConnection", connInfo);
      //删除关系信息
      commit("removeRelationById", targetId);
    }
  }
}
export default store;
